import $cache from '@/plugins/cache'
export default class ShopStore {
  tokens: AuthenticationTokens
  private readonly USERINFO_CACHE_KEY = 'LOGIN_INFO_CACHE_KEY'
  constructor() {
    this.tokens = $cache.cookie.get(this.USERINFO_CACHE_KEY)
  }

  public getAccessToken(): string {
    if (this.tokens != null) {
      return this.tokens.access_token
    }
    return null
  }
  public getRefreshToken(): string {
    if (this.tokens != null) {
      return this.tokens.refresh_token
    }
    return null
  }

  setTokens(tokens: AuthenticationTokens, rememberMe = false) {
    this.tokens = tokens
    // 如果 rememberMe 为true，那持久化
    const expires = (tokens.refresh_token_expire_in - Date.now()) / 1000 / 60 / 60 / 24
    $cache.cookie.set(this.USERINFO_CACHE_KEY, tokens, rememberMe ? { expires } : null)
  }
  clearLoginState() {
    $cache.cookie.remove(this.USERINFO_CACHE_KEY)
    this.tokens = null
  }
  isRefreshTokenExpired() {
    if (this.tokens == null) return true
    return Date.now() > this.tokens.refresh_token_expire_in
  }
}
